﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ilanver.Core
{
    public static class FileCache
    {
        public static T RetrieveFromCache<T>(string path) where T : class
        {
            if (String.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException("path");

            try
            {
                using (FileStream file = File.Open(path, FileMode.Open))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    return bf.Deserialize(file) as T;
                }
            }
            catch
            {
                return null;
            }
        }

        public static void StoreInCache<T>(T obj, string path) where T : class
        {
            if (obj == null)
                throw new ArgumentNullException("obj");
            if (String.IsNullOrWhiteSpace(path))
                throw new ArgumentNullException("path");

            using (FileStream file = File.Open(path, FileMode.Create))
            {
                new BinaryFormatter().Serialize(file, obj);
            }
        }
    }
}
